package com.endava.graduates.controller;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.endava.graduates.model.LoginForm;

@Controller
@RequestMapping("loginform.htm")
public class LoginController {
	@RequestMapping(method = RequestMethod.GET)
	public String showForm(Map model) {
		LoginForm loginForm = new LoginForm();
		model.put("loginForm", loginForm);
		return "loginform";
	}

	/*
	 * @RequestMapping(method = RequestMethod.POST) public String
	 * processForm(LoginForm loginForm, BindingResult result, Map model) {
	 * String userName = "admin"; String password = "root"; if
	 * (result.hasErrors()) { return "loginform";
	 * 
	 * } loginForm = (LoginForm) model.get("loginForm"); if
	 * (!loginForm.getUserName().equals(userName) ||
	 * !loginForm.getPassword().equals(password)) { return "loginerror"; }
	 * model.put("loginForm", loginForm); return "loginsuccess"; }
	 */

	@RequestMapping(method = RequestMethod.POST)
	public String processForm(LoginForm loginForm, BindingResult result,
			ModelMap model) {
		model.addAttribute("username", loginForm.getUsername());
		String userName = loginForm.getUsername();

		// String nume=
		// (udi.getUserByUsername(loginForm.getUserName())).getFirstName();
		System.out.println(userName);

		String password = "root";
		if (result.hasErrors()) {
			return "loginform";

		}
		loginForm = (LoginForm) model.get("loginForm");
		if (!loginForm.getUsername().equals(userName)
				|| !loginForm.getPassword().equals(password)) {
			return "loginerror";
		}
		model.put("loginForm", loginForm);
		return "loginsuccess";
	}
}